package com.yeyks.app.config;

import com.mongodb.MongoClientOptions;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoClientFactory;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = "com.yeyks.**.mongodb.repository")
public class MongodbConfig {

    @Primary
    @Bean("mongoProperties")
    public MongoProperties mongoProperties() {
        return new MongoProperties();
    }

    @Primary
    @Bean("mongoClientFactory")
    public MongoClientFactory mongoClientFactory(
            @Qualifier("mongoProperties") MongoProperties mongoProperties
            , Environment environment) {
        return new MongoClientFactory(mongoProperties, environment);
    }

    @Primary
    @Bean("mongoClientOptions")
    public MongoClientOptions mongoClientOptions(ObjectProvider<MongoClientOptions> options) {
        return MongoClientOptions.builder().build();
    }

    @Primary
    @Bean("mongoDbFactory")
    public MongoDbFactory mongoDbFactory(
            @Qualifier("mongoProperties") MongoProperties mongoProperties
            , @Qualifier("mongoClientFactory") MongoClientFactory mongoClientFactory
            , @Qualifier("mongoClientOptions") MongoClientOptions mongoClientOptions) throws Exception {
        return new SimpleMongoDbFactory(mongoClientFactory.createMongoClient(mongoClientOptions), mongoProperties.getDatabase());
//        return new SimpleMongoDbFactory(new MongoClient(storageMongoProperties.getHost(), storageMongoProperties.getPort()),storageMongoProperties.getDatabase());
    }

    @Primary
    @Bean("mongoTemplate")
    public MongoTemplate mongoTemplate(
            @Qualifier("mongoDbFactory") MongoDbFactory mongoDbFactory
    ) throws Exception {
        //remove _class
        MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory), new MongoMappingContext());
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));

        return new MongoTemplate(mongoDbFactory, converter);
    }

}
